<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

/**
 * 第4题画系统图，由于时间原因，我简单说下大概如下：
 * 1.注册路由 ---> 2.创建控制器 ---> 3. 控制器中获取数据库数据 ---> 4.在视图中展示数据
 * 本来我也想创建控制器，但是就一个例子的话，也可以直接在路由器中写上，如有规范需求，我也会遵守规范操作
**/

/**
 * 加分题的话，我平常使用laradock，所以也比较常用docker来部署环境
 */
Route::post('/test', function () {
    try {
        $id1 = request('id1');
        $id2 = request('id2');
        $test = \App\Test::where('id1', $id1)->where('id2', $id2)->first();
        if ($test) {
            return response()->json([
                'user_id' => $test->user_id,
            ]);
        } else {
            $insert_data = [
                'user_id' => gen_uuid(),
                'id1' => rand(1, 1000),
                'id2' => rand(1, 1000),
            ];
            \App\Test::create($insert_data);
            return response()->json([
                'user_id' => $insert_data['user_id'],
            ]);
        }
    } catch (\Exception $exception) {
        \Log::error('错误信息' . $exception->getMessage());
        return response()->json([
            'message' => '服务器繁忙，请稍后重试',
        ]);
    }

});

function gen_uuid()
{
    $uuid = array(
        'time_low' => 0,
        'time_mid' => 0,
        'time_hi' => 0,
        'clock_seq_hi' => 0,
        'clock_seq_low' => 0,
        'node' => array()
    );

    $uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
    $uuid['time_mid'] = mt_rand(0, 0xffff);
    $uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
    $uuid['clock_seq_hi'] = (1 << 7) | (mt_rand(0, 128));
    $uuid['clock_seq_low'] = mt_rand(0, 255);

    for ($i = 0; $i < 6; $i++) {
        $uuid['node'][$i] = mt_rand(0, 255);
    }

    $uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
        $uuid['time_low'],
        $uuid['time_mid'],
        $uuid['time_hi'],
        $uuid['clock_seq_hi'],
        $uuid['clock_seq_low'],
        $uuid['node'][0],
        $uuid['node'][1],
        $uuid['node'][2],
        $uuid['node'][3],
        $uuid['node'][4],
        $uuid['node'][5]
    );

    return $uuid;
}
